package com.butterfly.web.pages;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.tapestry5.annotations.Cached;
import org.apache.tapestry5.annotations.InjectComponent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.beaneditor.BeanModel;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.internal.beaneditor.BeanModelUtils;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.BeanModelSource;

import com.butterfly.domain.entity.Merchant;
import com.butterfly.service.MerchantService;

public class Merchants {
	
	@Inject
	private MerchantService merchantService;
	@Inject
	private BeanModelSource beanModelSource;
	@Inject
	private Messages messages;
	
	@Property
	@Persist
	private Merchant searchCriteria;
	
	@Property
	private Merchant merchantRow;
	
	@InjectComponent
	private Form searchMerchantForm;
	
	void setupRender() {
		searchCriteria = new Merchant();
	}
	
	void onNew() {
		
	}
	
	void onValidateFromSearchMerchantForm() {
		if(StringUtils.isBlank(searchCriteria.getCode()) && StringUtils.isBlank(searchCriteria.getName())) { 
			searchMerchantForm.recordError("Please fill in at least one search criteria");
		}
	}
	
	@Cached
	public List<Merchant> getMerchants() {
		return merchantService.findBy(searchCriteria);
	}
	
	public BeanModel<Merchant> getMerchantGridModel() {
		BeanModel<Merchant> model = beanModelSource.createDisplayModel(Merchant.class, messages);
		BeanModelUtils.add(model, "code, name, enabled");
		
		return model;
	}
		
}
